import React, { useState } from 'react'
import { Button, View } from '@tarojs/components'
import { AtTextarea, AtImagePicker } from 'taro-ui'
import styles from './index.module.less'
import { useRequest } from 'ahooks'
import { uploadFilerequest, request } from '../../utils/request'
import { getCurrentInstance } from '@tarojs/taro'

const createFunc = (data) => {
  return request('post', '/app/postbar', data)
}
const createRecruitFunc = (data) => {
  return request('post', '/app/recruit', data)
}
const initState = {
  content: "",
  pictureIds: []
}
const initFiles = []
const CreateBark: React.FC<{

}> = () => {
  // @ts-ignore
  const { type } = getCurrentInstance().router.params
  const [data, setData] = useState({ ...initState })
  const [files, setFiles] = useState([...initFiles])
  const create = useRequest(createFunc, {
    manual: true,
    onSuccess: () => {
      setFiles([...initFiles])
      setData({ ...initState })
    }
  })
  const createRecruit = useRequest(createRecruitFunc, {
    manual: true,
    onSuccess: () => {
      setFiles([...initFiles])
      setData({ ...initState })
    }
  })

  const onChange = (e: Array<any>, operationType: string, index: number) => {
    if (operationType === 'add') {
      uploadFilerequest('/app/postbar/images', e[files.length].url).then((res) => {
        // @ts-ignore
        setData({ pictureIds: [...data.pictureIds, ...res], content: data.content })
        // @ts-ignore
        setFiles([...files, { url: e[files.length].url }])
      })
    } else {
      // @ts-ignore
      setFiles(e)
      setData({
        content: data.content,
        pictureIds: data.pictureIds.filter((item, i) => {
          if (i !== index) {
            return item
          }
        })
      })
    }
  }
  return (
    <View className={styles.textArea}>
      {/* @ts-ignore */}
      <AtTextarea value={data.content}
        height={400}
        onChange={(e) => { setData({ content: e, pictureIds: data.pictureIds }) }}
        maxLength={400}
        placeholder='你的问题是...' />
      <AtImagePicker multiple={false}
        length={4}  //单行的图片数量
        files={files}
        onChange={onChange}
        showAddBtn={true} />
      <Button type='primary' loading={type === 'bark' ? create.loading : createRecruit.loading} onClick={() => type === 'bark' ? create.run(data) : createRecruit.run(data)}>保 存</Button>
    </View>
  )
}

export default CreateBark